package com.alex.webnote.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alex.common.ILogger;
import com.alex.common.cache.CacheKeys;
import com.alex.common.cache.CommonCacheManager;
import com.alex.common.tools.DateUtils;
import com.alex.webnote.dao.WebNoteDao;
import com.alex.webnote.domain.WebNotePO;
import com.alex.webnote.domain.WebNoteState;
import com.alex.webnote.domain.WebNoteSummary;

@Controller
@RequestMapping("/show")
public class ShowController {

	private static final int SUMMARY_SHOW_SIZE = 10;

	private static final int ALL_SHOW_SIZE = 100;

	@Autowired
	private WebNoteDao webNoteDao;

	@RequestMapping(value = "all", method = { RequestMethod.GET })
	public String allat1(Model model) {
		return all(model, "1");
	}

	@RequestMapping(value = "all/{pagenum}", method = { RequestMethod.GET })
	public String all(Model model, @PathVariable String pagenum) {
		int iPagenum = 1;
		try {
			iPagenum = Integer.parseInt(pagenum);
		} catch (NumberFormatException e) {
			// ign
		}

		List<Object[]> list = webNoteDao.queryAllByCreateTimePage(iPagenum,
				ALL_SHOW_SIZE);
		List<WebNotePO> webNotes = new ArrayList<WebNotePO>(list.size());
		String dateSplit = "";
		for (Object[] objects : list) {
			BeanWrapper bw = new BeanWrapperImpl(WebNotePO.class);
			int i = 0;
			bw.setPropertyValue("id", objects[i++]);
			bw.setPropertyValue("name", objects[i++]);
			bw.setPropertyValue("alias", objects[i++]);
			bw.setPropertyValue("createTime", objects[i++]);
			bw.setPropertyValue("updateTime", objects[i++]);
			bw.setPropertyValue("hots", objects[i++]);
			WebNotePO po = (WebNotePO) bw.getWrappedInstance();
			String test = DateUtils.getDateYearMonthChinese(po.getCreateTime());
			if (!dateSplit.equals(test)) {
				WebNotePO spo = new WebNotePO();
				spo.setId(-1L);
				spo.setName(test);
				dateSplit = test;
				webNotes.add(spo);
			}
			webNotes.add(po);
		}

		model.addAttribute("webNotes", webNotes);
		model.addAttribute("pagenum", iPagenum);
		return "webnote/all";
	}

	@RequestMapping(value = "summary", method = { RequestMethod.GET })
	public String summary(Model model) {

		List<WebNoteSummary> rt = CommonCacheManager.getInstance().get(
				CacheKeys.WebNoteSummaryList, "_");

		if (rt == null || rt.size() == 0) {
			List<WebNotePO> hotsList = webNoteDao
					.querySummaryByHots(SUMMARY_SHOW_SIZE);
			if (hotsList != null && hotsList.size() > 0) {
				int loops = hotsList.size() > SUMMARY_SHOW_SIZE ? SUMMARY_SHOW_SIZE
						: hotsList.size();
				rt = new ArrayList<WebNoteSummary>(loops);
				Set<Long> idSet = new HashSet<Long>(loops);
				List<WebNotePO> updatetimeList = webNoteDao
						.querySummaryByUpdatetime(SUMMARY_SHOW_SIZE);
				for (int i = 0; i < loops; i++) {
					WebNotePO poHots = hotsList.get(i);
					if (!idSet.contains(poHots.getId())) {
						rt.add(poHots.toSummary());
						idSet.add(poHots.getId());
						// check
						if (idSet.size() > SUMMARY_SHOW_SIZE) {
							break;
						}
					}

					WebNotePO poUpdatetime = updatetimeList.get(i);
					if (!idSet.contains(poUpdatetime.getId())) {
						rt.add(poUpdatetime.toSummary());
						idSet.add(poUpdatetime.getId());
						// check
						if (idSet.size() > SUMMARY_SHOW_SIZE) {
							break;
						}
					}
				}
				CommonCacheManager.getInstance().put(
						CacheKeys.WebNoteSummaryList, "_", rt);
			}
		} else {
			ILogger.logger_common
					.debug("Cache hit CacheKeys.WebNoteSummaryList.");
		}

		model.addAttribute("summary", rt);
		return "webnote/summary";
	}

	@RequestMapping(value = "article/{idOrAlias}", method = { RequestMethod.GET })
	public String show(@PathVariable String idOrAlias,
			HttpServletRequest request, HttpServletResponse response,
			Model model) throws IOException {
		if (NumberUtils.isDigits(idOrAlias)) {
			// 是数字，需要永久定位到别名
			WebNotePO webNote = webNoteDao.find(Long.valueOf(idOrAlias), null,
					true);
			if (webNote != null) {
				response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());
				response.sendRedirect("/webnote/show/" + webNote.getAlias());
				return null;
			}
		}
		// 是别名
		WebNotePO webNote = webNoteDao.findByAlias(idOrAlias, null, true,
				WebNoteState.PUBLISHED.ordinal());
		if (webNote == null) {
			// 别名错误
			response.setStatus(HttpStatus.NOT_FOUND.value());
			return null;
		}
		model.addAttribute("webNote", webNote);

		// 增加计数
		// counterService.incrCounter(webNoteDao,
		// Constants.APP_NAME_WEBNOTE_HOTS,
		// webNote.getId() + "", request);
		return "webnote/show";
	}
}
